package com.yl.message.service

import com.alibaba.fastjson.JSONObject
import com.yl.common.control.ResponseBody
import com.yl.message.common.annotation.MsgTypeHandler
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextRefreshedEvent
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap

private val log = LoggerFactory.getLogger(MessageService::class.java)!!

interface MessageService {
	fun send(config: JSONObject, userId: Long, msgBody: JSONObject): ResponseBody


}

private val messageServices: ConcurrentMap<String, MessageService> by lazy {
	ConcurrentHashMap()
}

fun getMessageService(name: String): MessageService? {
	if (!messageServices.containsKey(name)) {
		return null
	}

	return messageServices[name] ?: run {
		log.error("指定的messageServices名称不存在。。请检查。名称:{}", name)
		null
	}
}


@Suppress("unused")
@Component
class ConditionTypeListener : ApplicationListener<ContextRefreshedEvent> {
	override fun onApplicationEvent(event: ContextRefreshedEvent) {
		val beans = event.applicationContext.getBeansWithAnnotation(MsgTypeHandler::class.java)
		for ((_, bean) in beans) {
			val typeHandler: MsgTypeHandler = bean.javaClass.getAnnotation(MsgTypeHandler::class.java)
			messageServices[typeHandler.value.value] = bean as MessageService
		}
	}
}


